package com.tanhao.takeaway.commom;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;


@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandle {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> excptionHandler(SQLIntegrityConstraintViolationException exception){
             if(exception.getMessage().contains("Duplicate entry")){
                 String[] s = exception.getMessage().split(" ");
                 return R.error(s[2]+"出错了,已存在");
             }

             return R.error("未知错误");

    }

    @ExceptionHandler(CustomException.class)
    public R<String> CustomException(CustomException e){
        log.error(e.getMessage());
        return R.error(e.getMessage());
    }
}
